package cn.admobiletop.adsuyi.adapter.toutiao.listener;

import android.os.Handler;
import android.os.Looper;
import android.view.View;

import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;

import java.util.ArrayList;
import java.util.List;

import cn.admobiletop.adsuyi.ad.ADSuyiNativeAd;
import cn.admobiletop.adsuyi.ad.data.ADSuyiNativeAdInfo;
import cn.admobiletop.adsuyi.ad.listener.ADSuyiNativeAdListener;
import cn.admobiletop.adsuyi.adapter.toutiao.data.NativeExpressAdInfo;
import cn.admobiletop.adsuyi.config.ADSuyiErrorConfig;
import cn.admobiletop.adsuyi.util.ADSuyiAdUtil;

/**
 * @author ciba
 * @description 信息流广告监听
 * @date 2020/4/3
 */
public class NativeExpressAdListener extends BaseAdListener<ADSuyiNativeAdListener> implements TTAdNative.NativeExpressAdListener {
    private int width;
    private int height;
    private String posId;
    private ADSuyiNativeAd nativeAd;
    private List<ADSuyiNativeAdInfo> tempNativeAdInfoList;
    private List<ADSuyiNativeAdInfo> nativeAdInfoList;
    private int finishCount;
    private int totalCount;
    private Handler handler = new Handler(Looper.getMainLooper());

    public NativeExpressAdListener(String posId, int width, int height, ADSuyiNativeAd nativeAd, String platformPosId, ADSuyiNativeAdListener adListener) {
        super(platformPosId, adListener);
        this.nativeAd = nativeAd;
        this.posId = posId;
        this.width = width;
        this.height = height;
    }

    @Override
    public void onError(final int code, final String message) {
        if (handler != null) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    onAdFailed(code, message);
                }
            });
        }
    }

    @Override
    public void onNativeExpressAdLoad(List<TTNativeExpressAd> nativeExpressAdList) {
        if (nativeExpressAdList == null || nativeExpressAdList.isEmpty()) {
            if (handler != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onAdFailed(ADSuyiErrorConfig.AD_FAILED_AD_IS_EMPTY, ADSuyiErrorConfig.MSG_AD_FAILED_AD_IS_EMPTY);
                    }
                });
            }
        } else if (getAdListener() != null && !ADSuyiAdUtil.isReleased(nativeAd)) {
            tempNativeAdInfoList = new ArrayList<>();
            nativeAdInfoList = new ArrayList<>();
            totalCount = nativeExpressAdList.size();

            for (int i = 0; i < nativeExpressAdList.size(); i++) {
                TTNativeExpressAd ttNativeExpressAd = nativeExpressAdList.get(i);
                if (ttNativeExpressAd != null) {
                    NativeExpressAdInfo nativeExpressAdInfo = new NativeExpressAdInfo(posId, width, height, nativeAd.getActivity(), getPlatformPosId()) {
                        @Override
                        public void onRenderFail(View view, String s, int i) {
                            checkRenderFinish(false, this);
                        }

                        @Override
                        public void onRenderSuccess(View view, float v, float v1) {
                            checkRenderFinish(true, this);
                        }
                    };
                    tempNativeAdInfoList.add(nativeExpressAdInfo);

                    nativeExpressAdInfo.setAdListener(getAdListener());
                    nativeExpressAdInfo.setAdapterAdInfo(ttNativeExpressAd);
                }
            }
        }
    }

    /**
     * 释放资源
     */
    @Override
    public void release() {
        super.release();
        nativeAd = null;

        ADSuyiAdUtil.releaseList(nativeAdInfoList);
        nativeAdInfoList = null;

        ADSuyiAdUtil.releaseList(tempNativeAdInfoList);
        tempNativeAdInfoList = null;

        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    /**
     * 检查是否渲染完成
     *
     * @param success             是否渲染成功
     * @param nativeExpressAdInfo 模板广告对象
     */
    private void checkRenderFinish(boolean success, NativeExpressAdInfo nativeExpressAdInfo) {
        finishCount++;
        if (success
                && nativeExpressAdInfo != null
                && !nativeExpressAdInfo.isReleased()
                && nativeAdInfoList != null
                && tempNativeAdInfoList != null) {
            tempNativeAdInfoList.remove(nativeExpressAdInfo);
            nativeAdInfoList.add(nativeExpressAdInfo);
        }
        if (finishCount >= totalCount) {
            if (handler != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getAdListener() != null && nativeAdInfoList != null && nativeAdInfoList.size() > 0) {
                            getAdListener().onAdReceive(nativeAdInfoList);
                        }
                        ADSuyiAdUtil.releaseList(tempNativeAdInfoList);
                        tempNativeAdInfoList = null;
                    }
                });
            }
        }
    }
}
